from flask import Blueprint, render_template, request, current_app, g, redirect, url_for
from models.books import BoardModel,BookModel
from flask_paginate import Pagination
from decorators import login_required
from models.user import UserModel,book_user_table
from exts import db
from sqlalchemy.sql import select
bp = Blueprint("front",__name__,url_prefix="")


@bp.get("/")
def index():
    boards = BoardModel.query.filter_by(is_active=1).all()
    # 获取board_id
    board_id = request.args.get("board_id",type=int,default=0)
    # 获取页码参数
    page = request.args.get('page',type=int,default=1)
    # 开始位置
    start = (page-1)*current_app.config.get('PER_PAGE_COUNT')
    # 结束位置
    end = start + current_app.config.get("PER_PAGE_COUNT")
    # 查询对象
    query_obj = BookModel.query.filter_by(is_active=True).order_by(BookModel.create_time.desc())
    # 判断board_id是否存在
    if board_id:
        query_obj = query_obj.filter_by(board_id=board_id)
    # 总共有多少数据
    total = query_obj.count()
    # 当前page下的列表
    books = query_obj.slice(start,end)
    # 分页对象
    pagination = Pagination(bs_version=4,page=page,total=total,outer_window=0,inner_window=2,alignment="center")
    context={
        'boards':boards,
        "books":books,
        "pagination":pagination,
        "current_board_id":board_id
    }
    return render_template("front/book_list.html",**context)


@bp.route("/book/detail/<int:book_id>")
def book_detail(book_id):
    book = BookModel.query.get(book_id)
    return render_template("front/book_detail.html",book=book)


# 借阅图书
@bp.route("/book/borrow/<int:book_id>")
@login_required
def borrow_book(book_id):
    # 分两步,第一步设置book的is_borrowed为true,第二步添加借阅表的数据
    book = BookModel.query.get(book_id)
    book.is_borrowed = True
    book.users.append(g.user)

    db.session.commit()
    return redirect(url_for("front.book_detail",book_id=book.id))


# 查看借阅记录
@bp.route("/borrow_info")
@login_required
def borrow_info():
    books = g.user.books
    ret = db.session.execute(book_user_table.select().filter_by(user_id=g.user.id)).fetchall()
    i=0
    for book in books:
        setattr(book,'borrow_time',ret[i].borrow_time)
        setattr(book,'is_return',ret[i].is_return)
        i=i+1
    return render_template("front/borrow_info.html",books=books)